<?php
declare(strict_types=1);

namespace App\Service;

use App\Helper\Log;
use App\Helper\Util;
use Hyperf\DbConnection\Db;
use App\Service\StatisrecService;
use GuzzleHttp\Client;

/**
 * 小程序服务
 */
class ProgramService 
{
    private $appid = "";
    private $appsecret = "";
    /**
     * [__construct description] 构造函数
     */
    public function __construct()
    {
        $wxconfig = config('wxconfig', []);
        $gzhconfig = $wxconfig['mini_program']??[];
        $this->appid = $gzhconfig['appid']??NULL;
        $this->appsecret = $gzhconfig['appsecret']??NULL;
    }
    /**
     * 处理文字消息
     * [handleText description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function handleText($params)
    {
        $content = $params['Content']??"";
        $openid = $params['FromUserName']??"";
        switch ($content) {
            case '1':
                $this->download($openid);
                $res = "success";
                break;
            default:
                $res = "success";
                break;
        }
        return $res;
    }
    /**
     * 下载地址
     * [download description]
     * @param  [type] $touser [description]
     * @return [type]         [description]
     */
    public function download($touser)
    {
        $access_token = Util::getWxAccessToken($this->appid,$this->appsecret);
        $method = "POST";
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        $params = [
            'access_token' => $access_token,
            'touser' => $touser,
            'msgtype' => "text",
            'text' => [
                'content' => "<a href='https://qpphome.51sqbby.com/download.html'>点击下载APP</a>"
            ],
        ];

        Log::get("wx_send_programkefu_url")->info($url);
        $options = [
            'headers' => [
                'Content-Type'=>'application/json',
            ],
            'body' => json_encode($params, JSON_UNESCAPED_UNICODE)
        ];
        $response = (new Client())
            ->request($method, $url, $options)
            ->getBody()
            ->getContents();
        Log::get("wx_send_programkefu_res")->info($response);
        $response = json_decode($response,true);
        return $response;
    }
}
